package com.btkjgc.service.impl;

import com.btkjgc.models.*;
import com.btkjgc.service.intf.AdminUserManageService_Intf;
import com.btkjgc.utils.Constant;
import com.btkjgc.utils.DateUtils;
import com.btkjgc.utils.HibernateUtil;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by _ESE on 2015/2/9.
 */
@Component
public class AdminUserManageService_Impl implements AdminUserManageService_Intf
{

	static Logger logger = Logger.getLogger(AdminUserManageService_Impl.class);

	@Override
	public int getCount(AdminUser adminUser, String username, String entityname)
	{
		/*
		 * // 非超级管理员，只能查看当前换电站及下属换电站的维护人员账号 // 可以查看当前运营商或者子运营商的维护人员 //
		 * 超级管理员，可以查看所有用户 同时兼顾用户名(和运营商名称:暂未启用)
		 */
		String hql = "select count(*) FROM AdminUserV WHERE 1=1 ";
		List<String> parameter = new ArrayList<String>();
		int count = 0;
		if (adminUser.getId() != Constant.ADMIN_ENTITY)
		{// 非超级管理员，只能查看当前换电站及下属换电站的维护人员账号
			hql += " AND (parentid=? or entityid=?)";
			parameter.add(adminUser.getEntityid().toString());
			parameter.add(adminUser.getEntityid().toString());

		}
		// 超级管理员，可以查看所有用户
		if (username != null && username.length() > 0)
		{
			hql += " AND username like '%" + username + "%'";
		}
		if (entityname != null && entityname.length() > 0)
		{
			hql += " AND entityname like '%" + entityname + "%'";
		}
		String[] par = null;
		String[] temp = null;
		if (parameter.size() > 0)
		{
			par = new String[parameter.size()];
			temp = parameter.toArray(par);
		}
		count = HibernateUtil.executeCountQuery(hql, temp);
		return count;
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<AdminUser> getRecord(AdminUser adminUser, Integer pageIndex,
			Integer pageSize, String username, String entityname,
			String sortfield)
	{
		String hql = "from AdminUser  WHERE 1=1  ";
		List<String> parameter = new ArrayList<String>();
		if (adminUser.getId() != Constant.ADMIN_ENTITY)
		{// 非超级管理员，只能查看当前换电站及下属换电站的维护人员账号
			hql += " AND (parentid=? or entityid=?)";
			parameter.add(adminUser.getEntityid().toString());
			parameter.add(adminUser.getEntityid().toString());

		}
		// 超级管理员，可以查看所有用户
		if (username != null && username.length() > 0)
		{
			hql += " AND username like '%" + username + "%'";
		}
		if (entityname != null && entityname.length() > 0)
		{
			hql += " AND entityname like '%" + entityname + "%'";
		}
		String[] par = null;
		String[] temp = null;
		if (parameter.size() > 0)
		{
			par = new String[parameter.size()];
			temp = parameter.toArray(par);
		}
		List<AdminUser> adminUserList = HibernateUtil.executeQuery(hql,
				pageIndex, pageSize, temp);
		return adminUserList;
	}
 
	@SuppressWarnings("unchecked")
	@Override
	public Integer insertAdminUser(String addEntityId, String addUserName,
			String addPassword, String addEntityName, String addRole,
			String addSex, String addPhone, String addEmail)
	{
		List<AdminUser> judgeUserList = HibernateUtil.executeQuery(
				"FROM AdminUser where username = ?",
				new String[] { addUserName });
		if (judgeUserList.size() > 0) { return -2; }

		AdminUser adminUser = new AdminUser();
		String hql = "from Entity where id=?";
		String[] para = new String[] { addEntityId };
		if (addEntityId != null)
		{
			hql = "from Entity where id=?";
			para = new String[] { addEntityId + "" };
		}

		try
		{
 
				adminUser.setUsername(addUserName);
				adminUser.setPassword(DigestUtils.md5Hex(addPassword));
				adminUser.setPhone(addPhone);
				adminUser.setSex(addSex);
				adminUser.setEmail(addEmail);
				adminUser.setCreatedate(DateUtils.getCurrentFormatDate());
				adminUser.setLogintimes(0);
				HibernateUtil.save(adminUser);
				// 插入role，admin_user_role
				String roleString = "from Role where name=?";
				String[] roleparam = new String[] { addRole };
				Role role = (Role) HibernateUtil.objectQuery(roleString,
						roleparam);
				if (role != null)
				{
					String auhql = "FROM AdminUser where username=?";
					AdminUser au = (AdminUser) HibernateUtil.objectQuery(auhql,
							new String[] { addUserName });
					AdminUserRole adminUserRole = new AdminUserRole();
					adminUserRole.setUserid(au.getId());
					adminUserRole.setRoleid(role.getId());
					HibernateUtil.save(adminUserRole);
					return 1;
				}
			 
		}
		catch (Exception e)
		{
			return -11;
		}
		return -1;
	}

	@Override
	public void deleteById(Integer adminUserId)
	{
		String hql = "delete from AdminUser where id=?";
		String param[] = { String.valueOf(adminUserId) };
		String hql2 = "delete FROM AdminUserRole where userid = ?";
		HibernateUtil.executeUpdate(hql, param);
		HibernateUtil.executeUpdate(hql2, param);
	}

	@Override
	public void resetPWById(Integer adminUserId)
	{
		String hql = "update AdminUser set password=? where id=?";
		String param[] = { DigestUtils.md5Hex(Constant.DEFAULTPW),
				String.valueOf(adminUserId) };
		HibernateUtil.executeUpdate(hql, param);//
	}

	@Override
	public void changePWById(Integer adminUserId, String PW)
	{
		String hql = "update AdminUser set password=? where id=?";
		String param[] = { DigestUtils.md5Hex(PW), String.valueOf(adminUserId) };
		HibernateUtil.executeUpdate(hql, param);//
	}

	@Override
	public void changePWByName(String username, String PW)
	{
		String hql = "update AdminUser set password=? where username=?";
		String param[] = { DigestUtils.md5Hex(PW), PW };
		HibernateUtil.executeUpdate(hql, param);//
	}

	@Override
	public void updateAdminUserRole(int adminUserId, String roleName)
	{
		String hql = "FROM Role where name=?";
		Role role = (Role) HibernateUtil.objectQuery(hql,
				new String[] { roleName });
		String hql2 = "update AdminUserRole set roleid=? where userid=?";
		String param[] = { role.getId().toString(), String.valueOf(adminUserId) };
		HibernateUtil.executeUpdate(hql2, param);

	}
}
